# -*- coding: utf-8 -*-
import threading
import time

from Util.util import checkACC2Byte


class rxHYB01PowerThread(threading.Thread):
    def __init__(self, StateCtrl):
        super(rxHYB01PowerThread, self).__init__()
        self.Ctrl = StateCtrl
        self.__flag = threading.Event()  # 用于暂停线程的标识
        self.__flag.set()  # 设置为True
        self.__running = threading.Event()  # 用于停止线程的标识
        self.__running.set()  # 将running设置为True
        self.FrameHeader = [0x55, 0xAA]  # 帧头
        self.FrameLength = 70  # 定帧帧长
        pass

    def run(self):
        while self.Ctrl.Ser.isOpen() and self.__running.isSet():
            time.sleep(0.005)
            self.__flag.wait()
            if self.Ctrl.Ser.isOpen():
                if self.Ctrl.Ser.inWaiting():
                    frames = list(self.Ctrl.Ser.read(self.FrameHeader.__len__()))
                    if frames == self.FrameHeader:
                        FrameData = list(self.Ctrl.Ser.read(self.FrameLength - self.FrameHeader.__len__()))
                        FrameData.insert(0, frames[1])
                        FrameData.insert(0, frames[0])
                        AccCheck = checkACC2Byte(FrameData[:(self.FrameLength - self.FrameHeader.__len__())])
                        if AccCheck[0] == FrameData[self.FrameLength - 2] and AccCheck[1] == FrameData[self.FrameLength - 1]:  # 校验和正确
                            self.Ctrl.OnReceiveData(FrameData)
                            pass


    def pause(self):
        self.__flag.clear()  # 设置为False, 让线程阻塞

    def resume(self):
        self.__flag.set()  # 设置为True, 让线程停止阻塞

    def stop(self):
        self.__flag.set()  # 将线程从暂停状态恢复, 如何已经暂停的话
        self.__running.clear()  # 设置为False